<?php


namespace App\Http\Controllers\user;


use App\Engine\BaseController;
use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Http\service\ActiveService;
use App\Http\service\AuthService;
use App\Http\service\ValidateService;
use App\Http\service\XcxService;
use App\Jobs\ChatMsgJob;
use App\Jobs\GetCustomJob;
use App\Jobs\ShareLogJob;
use App\Jobs\ThroughLogJob;
use App\Models\Active;
use App\Models\Collect;
use App\Models\Custom;
use App\Models\EggLog;
use App\Models\HomeSet as HomeSetModel;
use App\Models\Image as ImageModel;
use App\Models\ImageBanners;
use App\Models\Sys;
use App\Models\ThroughLog;
use App\Models\TurntableLog;
use Illuminate\Support\Facades\DB;
use function app\Utils\go;
use App\Models\Appointment as AppointmentModel;
use App\Models\TurntableLog as LogModel;
use App\Models\Article as ArticleModel;
use App\Models\Property as PropertyModel;
use App\Models\Type as TypeModel;
use App\Models\Banner as BannerModel;
use App\Models\Nav as NavModel;
use App\Models\User as UserModel;
use App\Models\TurntableActive as TurntableActiveModel;
use App\Models\Floor as FloorModel;
use App\Models\ChartLog as ChartLogModel;
use App\Models\CustomStar as CustomStarModel;
use App\Models\Live as LiveModel;
use App\Models\TxLog as TxLogModel;
use Illuminate\Support\Facades\Cache;
use App\Models\Notice as NoticeModel;




class Common extends BaseController
{

    /**
     * 提现核销
     */
    public function tx_hx()
    {
        (new AuthService())->check_opcode($this->get["code"]);
        $log=TxLogModel::where("id",$this->get["id"])->where("state",0)->first();
        if (!$log)
            throw new ApiException("申请不存在或已过期");

        $res=Cache::lock("hx_application")->get(function ()use ($log){
            $user=UserModel::where("id",$log["uid"])->first();
            if ($user["balance"]<$log["price"]){
                throw new ApiException("余额不足");
            }
            DB::beginTransaction();
            try {
                $user->decrement("balance",$log["price"]);
                $res=TxLogModel::where("id",$log["id"])->update(["state"=>1]);
                DB::commit();
                return $res;
            }catch (\Exception $exception){
                DB::rollBack();
                throw new ApiException("提现失败");
            }

        });
        return go($res);

    }

    /**获取户型
     * @return array
     */
    public function get_type()
    {
        $res=TypeModel::get();
        return go($res);
    }

    public function get_notice()
    {
        $res=NoticeModel::orderBy("sort","asc")->get();
        return go($res);
    }


    public function getPlaybacks()
    {
        $live=LiveModel::where("id",$this->get["id"])->first();
        if (!$live)
            throw new ApiException("房间不存在");
        if ($live["live_status"]==103&&!$live["play_back_url"]){
            $yum=(new XcxService())->getPlaybacks($live["roomid"]);
            if($yum["errmsg"]==0){
                LiveModel::where("id",$live["id"])->update(["play_back_url"=>$yum["live_replay"]]);
                $live=LiveModel::where("id",$this->get["id"])->first();
            }
        }

        return  go($live);

    }


    /**获取首页数据
     * @return array
     */
    public function get_index()
    {
        $res=HomeSetModel::orderBy("sort","asc")->get();
        return go($res);
    }

    /**
     * 点赞顾问
     */
    public function star_custom()
    {
        $model=new CustomStarModel();
        $where=[
            "uid"=>TokenService::getCurrentUid(),
            "aid"=>$this->get["aid"]
        ];
        $res=$model->where($where)->first();
        if ($res){
            $res=$model->where($where)->delete();
        }else{
            $res=$model->create($where);
        }
        $res=Custom::with(["through.user","star"])->where("id",$this->get["aid"])->first();
        $res["is_star"]=CustomStarModel::where(["uid"=>TokenService::getCurrentUid(),"aid"=>$this->get["aid"]])->first();
        return go($res);
    }

    /**获取参与抽奖人数
     * @return array
     */
    public function get_prize_users()
    {
        $res=LogModel::groupBy("uid")->get();
        return go(["count"=>count($res)]);
    }

    /**获取所有楼层
     * @return array
     */
    public function get_floor()
    {
        $res=FloorModel::get();
        return go($res);
    }

    /**
     * @return array
     */
    public function get_TurntableActive()
    {
        $sum=TurntableActiveModel::sum("weight");
        $res=TurntableActiveModel::orderBy("id","asc")->get()->map(function ($item)use($sum){
            $item["prop"]=72*$item["weight"]/(float)$sum;
            $item["prop"]=round($item["prop"],0);
            $item["state"]=false;
            return $item;
        });
        return go($res);
    }



    /**
     * 获取导航
     */
    public function get_nav()
    {
        $res=NavModel::where("hidden",0)->orderBy("sort","asc")->get();
        return go($res);
    }

    public function get_banners()
    {
        $res=BannerModel::where("hidden",0)->orderBy("sort","asc")->get();
        return go($res);
    }


    /**
     * 获取直播列表
     */
    public function get_live()
    {
        $where=[];
        if (isset($this->get["live_status"])){
            $where["live_status"]=$this->get["live_status"];
        }
        $res=LiveModel::with("user")->where($where)->orderBy("id","desc")->get();
        return go($res);
    }

    /**获取楼栋表
     * @return array
     */
    public function get_properties()
    {
        $res=PropertyModel::select(["id","name"])->get();
        return go($res);
    }

    /**获取系统配置
     * @return array
     */
    public function get_sys()
    {
        $key=["share_title","coupon_popup1","coupongoods_icon","coupongoods_bg","coupon_popup","coupon_bg","coupon_on","box_invite_user","user_box_limit","bind_box_mode","bind_box_limit","index_win_pic_two","tree_rule","index_win_pic","index_jump_type","index_jump_page","tree_total","live_nav_bg","tree_reward_limit","tx_min_price","tree_change","tree_limit","home_nav_bg","follow_ghz_url","follow_ghz_bg","home_nav_color","pay_tel_icon","pay_icon","cpy_name","reward_bg","reward_icon","game_bg","active_chick_icon","active_draw_icon","chick_nav","is_auth","identification_bg","project_detail_bg","project_param_bg","through_time","chick_rule","qrcode_nav_bg","gift_bg","invite_bg","appointment_bg","collect_bg","egg_get_bg","custom_bg","draw_bg","my_nav_bg","project_nav_bg","egg_icon","egg_bg","bind_phone_pic","through_time","sys_background","appointment_bg","active_icon","custom_icon","booking_bt","appointment_bg","blind_rule","coupon_bg","bind_icon","coupon_icon","coupon_rule","first_coupon","deduction_invitation_rules","blind_share_title"];
        $res=Sys::whereIn("key",$key)->get();
        $data=array();
        foreach ($res as $key=>$value){
            $data[$value['key']]=$value["value"];
        }
        return go($data);
    }

    /**id获取文章
     * @return array
     */
    public function get_article_id()
    {
        $res=ArticleModel::where("id",$this->get["id"])->first();
        return go($res);
    }

    public function get_article()
    {
        $res=ArticleModel::paginate($this->get["num"]);
        return go($res);
    }

    /**
     * 添加分享记录
     */
    public function add_shares()
    {
        ShareLogJob::dispatch($this->get["id"]);
        return go(["data"=>true]);
    }

    /**转盘抽奖
     * @return array
     * @throws \App\Exceptions\ApiException
     */
    public function draw_run()
    {
        return go((new ActiveService())->start_draw());
    }

    /**
     * 获取抽奖记录
     */
    public function get_draw_log()
    {
        $res=LogModel::where("uid",TokenService::getCurrentUid())->orderBy("id","desc")->paginate($this->get["num"]);
        return go($res);
    }

    /**
     * 添加分享记录
     */
    public function add_house_through()
    {
        $type="chick";

        if (isset($this->get["type"])){
            $type=$this->get["type"];
        }

        $data=[
            "uid"=>TokenService::getCurrentUid(),
            "type"=>$type
        ];
        ThroughLogJob::dispatch($data);
        return go(["data"=>true]);
    }

    public function get_show()
    {
        return go(["data"=>true]);
        $flg=false;
        $res=ThroughLog::where(["uid"=>TokenService::getCurrentUid(),"date"=>date("Y-m-d")])->count();
        $time=Sys::getValue("through_limit");
        if ($time>$res){
            $flg=true;
        }
        return go(["data"=>$flg]);
    }

    /**收藏项目
     * @return array
     */
    public function collect_house()
    {
        $collectModel=new Collect();
        if($this->post["state"]==0){
            $res=$collectModel->where(["uid"=>TokenService::getCurrentUid(),"house_id"=>$this->post["house_id"]])->delete();
        }else{
            $res=$collectModel->create(["uid"=>TokenService::getCurrentUid(),"house_id"=>$this->post["house_id"]]);
        }
        return go($res);
    }

    /**获取收藏列表
     * @return array
     */
    public function get_collectList()
    {
        $res=Collect::with("house")->where("uid",TokenService::getCurrentUid())->get();
        return go($res);
    }

    /**获取置业顾问
     * @return array
     */
    public function get_adviser()
    {
        if (isset($this->get["id"])){
            if($this->get["id"]){
                $res=Custom::with(["through.user","star"])->where("uid",$this->get["id"])->first();
                return  go($res);
            }
        }

        $uid=TokenService::getCurrentUid();
        $user=UserModel::where("id",$uid)->first();
        if (isset($user["invite_uid"])){
            $invite=UserModel::with("custom")->where(["id"=>$user["invite_uid"]])->first();
            if (isset($invite["custom"])){
                return  go($invite["custom"]);
            }
        }
        $custom=Custom::with(["through.user","star"])->inRandomOrder()->first();
        $job=[
            "uid"=>$uid,
            "aid"=>$custom["id"]
        ];
        $custom["is_star"]=CustomStarModel::where($job)->first();
        GetCustomJob::dispatch($job);
        return  go($custom);
    }

    public function get_custom()
    {
        $res=Custom::limit(5)->get();
        return go($res);
    }

    public function get_all_custom()
    {
        $data=array();
        $index=Custom::get();
        $data[]=$index;
        $data[]=Custom::orderBy("id",'asc')->get();
        $data[]=Custom::orderBy("id","desc")->get();
        return go($data);

    }

    public function get_image_banners()
    {
        $res=ImageBanners::where("type",$this->get["type"])->where("hidden",0)->orderBy("sort","asc")->get();
        return go($res);
    }



    /**申请预约
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function appointment()
    {
        $model=new AppointmentModel();
        $this->validate($this->request,ValidateService::$appointmentRule,ValidateService::$appointmentMessage);
        $this->post=$model->filter_data($this->post);
        $this->post["uid"]=TokenService::getCurrentUid();
        $this->post["time"]=date("Y-m-d H:i:s");
        $res=AppointmentModel::create($this->post);
        return go($res);
    }

    /**获取预约记录
     * @return array
     */
    public function get_appointment_list()
    {
        $res=AppointmentModel::where("uid",TokenService::getCurrentUid())->paginate($this->get["num"]);
        return go($res);
    }

    /**
     * 获取活动中心文章
     */
    public function get_active()
    {
        $where=[];
        if(isset($this->get["search"])){
            if($this->get["search"]){
                $where[]=["name","like","%{$this->get['search']}%"];
            }
        }
        $res=Active::where($where)->paginate($this->get["num"]);
        return go($res);
    }

    /**获取领蛋记录
     * @return array
     */
    public function get_egg_logs()
    {
        $res=EggLog::where("uid",TokenService::getCurrentUid())->where("type",1)->where("state",$this->get["state"])->paginate($this->get["num"]);
        return go($res);
    }

    /**
     * 获取我的奖品
     */
    public function get_reward_log()
    {
        $res=TurntableLog::where("uid",TokenService::getCurrentUid())->where("state",$this->get["state"])->orderBy("id","desc")->paginate($this->get["num"]);
        return go($res);
    }

    public function save_chat()
    {

        ChatMsgJob::dispatch($this->post);
    }

    /**更新图片
     * @return array
     */
    public function uploads_image()
    {
        $path=$this->request->file('img')->store("uploads/talking");
        $res=ImageModel::create(["url"=>$path]);
        return go($res);
    }

    /**
     *获取聊天列表
     */
    public function get_chat_list()
    {


        $res=ChartLogModel::with(["user","custom"])->where("is_delete",null)->where(function ($query){
            $query->where("uid",TokenService::getCurrentUid())->orWhere("cid",TokenService::getCurrentUid());
        })->orderBy("id","desc")->groupBy("message_id")->get()->map(function ($item){
            if($item["cid"]==TokenService::getCurrentUid()){
                $item["type"]="custom";
            }else{
                $item["type"]="user";
            }
            return $item;
        });

        return go($res);

    }

}
